package com.example.demo.bo;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.example.demo.bo.FontsUtil.getSIMSUN;

/**
 * @author: linliquan
 * @date: 2018/10/9
 * @description:
 */
@Component
public class MakeWaterMark {


    public String watermarkWord() {

        //原文件所在文件夹
        String oldPath ="D:/" + File.separator + "waterTest" + File.separator + "old";
        //需要存储到的新位置
        String newPath = "D:/" + File.separator + "waterTest" + File.separator + "new";
        String imgPath = oldPath + File.separator + "中秋1.jpg";
       //文字倾斜度
        int degree=30;
            try {
                File sf = new File(newPath);
              //  String logoFileName = 0 + oldFileName;
                //要生成水印的原图
                File imageFile = new File(imgPath);
                Image image1 = ImageIO.read(imageFile);
                //原图宽度
                int width = image1.getWidth(null);
                //原图高度
                int height = image1.getHeight(null);
                //图片缓存对象
                BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                //绘图工具对象
                Graphics2D graphics2D = bufferedImage.createGraphics();
                //将原图放大或缩小后画下来:并且保持png图片放大或缩小后背景色是透明的而不是黑色
              /*  bufferedImage = graphics2D.getDeviceConfiguration().createCompatibleImage(width,height,Transparency.TRANSLUCENT);
                graphics2D.dispose();
                graphics2D = bufferedImage.createGraphics();*/
                graphics2D.drawImage(image1.getScaledInstance(image1.getWidth(null), image1.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
                    //水印文字的大小
                    int fontSize =50;
                    //水印文字的内容
                    String markText = "我是测试的字";
                    //水印文字位置 XY
                    int left = 80;
                    int top = 20;
                    String colorStr="ff00ff";
                    //水印文字的颜色
                    Color color = parseToColor(colorStr);
                    //水印文字的字体类型
                    String fontFamily = "微软雅黑";
                    //水印文字的粗细程度
                    int fontWeight =700;
                    Font font=font = new Font(fontFamily, fontWeight, fontSize);
                    //当服务器上没有字体，可以将字体放到项目中托管
                  //  Font font = getSIMSUN(fontWeight,fontSize);
                    //设置字体
                    graphics2D.setFont(font);
                    graphics2D.setColor(color);
                    // 消除java.awt.Font字体的锯齿
                    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                    graphics2D.rotate(Math.toRadians(degree),(double) width / 2, (double) height / 2);


                    //以下为水印位置调整，保证不能超出范围
                    int width1 = fontSize * getWordCount(markText) / 2;
                    int height1 = fontSize;
                    int widthDiff = width - width1;
                    int heightDiff = height - height1;
                    if (left > widthDiff) {
                        left = widthDiff;
                    }
                    if (top > heightDiff) {
                        top = heightDiff;
                    }
                    boolean isVertical=false;
                    // graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1));//设置透明度
                    if(isVertical){
                        addText_ShuPaiWenzi(left,top + fontSize,markText,graphics2D,font);
                    }else{
                        AttributedString ats = new AttributedString(markText);
                        ats.addAttribute(TextAttribute.FONT, font, 0, markText.length());
                        AttributedCharacterIterator iter = ats.getIterator();
                        //为图片添加文字水印
                        graphics2D.drawString(iter, left, top + fontSize);
                    }
                    graphics2D.dispose();//释放掉
                    if (!sf.exists()) {
                        sf.mkdirs();
                    }
                //我要获取当前的日期
                Date date = new Date();
                //设置要获取到什么样的时间
                SimpleDateFormat sdf = new SimpleDateFormat("HH_mm_ss");
                //获取String类型的时间
                String createdate = "中秋1"+sdf.format(date);
                String newFileName = sf.getPath() + File.separator+createdate + ".jpg";
                File myFile = new File(newFileName);
                ImageIO.write(bufferedImage, "jpg", myFile);
                imgPath = sf.getPath() + File.separator+createdate + ".jpg";

             /*   jdk1.8下不支持
             OutputStream os=null;
                os=new FileOutputStream(newFileName);
                JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(os);
                encoder.encode(bufferedImage);*/

                bufferedImage = null;
            } catch (Exception e) {
                e.printStackTrace();

                System.gc();
            } finally {

                System.gc();
            }
            return imgPath;



    }

    public String watermarkImage() {

        //原文件所在文件夹
        String oldPath ="D:/" + File.separator + "waterTest" + File.separator + "old";
        //需要存储到的新位置
        String newPath = "D:/" + File.separator + "waterTest" + File.separator + "new";
        String imgPath = oldPath + File.separator + "中秋1.jpg";
        try {
            File sf = new File(newPath);
            //  String logoFileName = 0 + oldFileName;
            //要生成水印的原图
            File imageFile = new File(imgPath);
            Image image1 = ImageIO.read(imageFile);
            //原图宽度
            int width = image1.getWidth(null);
            //原图高度
            int height = image1.getHeight(null);
            //图片缓存对象
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //绘图工具对象
            Graphics2D graphics2D = bufferedImage.createGraphics();



            //将原图放大或缩小后画下来:并且保持png图片放大或缩小后背景色是透明的而不是黑色
          /*  bufferedImage = graphics2D.getDeviceConfiguration().createCompatibleImage(width,height,Transparency.TRANSLUCENT);
            graphics2D.dispose();
            graphics2D = bufferedImage.createGraphics();*/
            graphics2D.drawImage(image1.getScaledInstance(image1.getWidth(null), image1.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            //要添加的水印的地址
            String logoPath=oldPath+ File.separator + "logo.png";;
            File logo=new File(logoPath);
            Image imageLogo = ImageIO.read(logo);
            //Logo宽度
            int widthLogo = imageLogo.getWidth(null);
            //Logo高度
            int heightLogo = imageLogo.getHeight(null);

            //水印文字位置 XY
            int left = 12;
            int top = 20;
            int widthDiff = width - widthLogo;
            int heightDiff = height - heightLogo;
            if (left > widthDiff) {
                left = widthDiff;
            }
            if (top > heightDiff) {
                top = heightDiff;
            }
            // graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1));//设置透明度
                //为图片添加图片水印
                graphics2D.drawImage(imageLogo, left, top,null);

            graphics2D.dispose();//释放掉
            if (!sf.exists()) {
                sf.mkdirs();
            }
            //我要获取当前的日期
            Date date = new Date();
            //设置要获取到什么样的时间
            SimpleDateFormat sdf = new SimpleDateFormat("HH_mm_ss");
            //获取String类型的时间
            String createdate = "中秋1_"+sdf.format(date);
            String newFileName = sf.getPath() + File.separator+createdate + ".jpg";
            File myFile = new File(newFileName);
            ImageIO.write(bufferedImage, "jpg", myFile);
            imgPath = sf.getPath() + File.separator+createdate + ".jpg";

             /*   jdk1.8下不支持
             OutputStream os=null;
                os=new FileOutputStream(newFileName);
                JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(os);
                encoder.encode(bufferedImage);*/

            bufferedImage = null;
        } catch (Exception e) {
            e.printStackTrace();

            System.gc();
        } finally {

            System.gc();
        }
        return imgPath;



    }



    public void addText_ShuPaiWenzi(int x,int y,String str,Graphics2D g,Font font){


        int strlength = str.length();
//获取字体宽度
        int t = g.getFontMetrics().stringWidth("str");
//竖排文字
        for(int i=0;i<strlength;i++){

            g.drawString(String.valueOf(str.charAt(i)), x, y);
            AttributedString ats = new AttributedString(String.valueOf(str.charAt(i)));
            ats.addAttribute(TextAttribute.FONT, font, 0, String.valueOf(str.charAt(i)).length());
            AttributedCharacterIterator iter = ats.getIterator();
            //为图片添加文字水印
            g.drawString(iter, x, y );

            y +=t;
        }
    }


    /**
     * @author: LinliQuan
     * @date: 2018/7/11 10:55
     * @description:把字符串表达的颜色值转换成java.awt.Color
     */
    public static Color parseToColor(final String c) {
        Color convertedColor = Color.ORANGE;
        try {
            convertedColor = new Color(Integer.parseInt(c, 16));
        } catch(NumberFormatException e) {
            // codes to deal with this exception
        }
        return convertedColor;
    }
    /**
     * 按字节获取字符串长度
     *
     * @param s
     * @return
     */
    public static int getWordCount(String s) {
        int length = 0;
        for (int i = 0; i < s.length(); i++) {
            int ascii = Character.codePointAt(s, i);
            if (ascii >= 0 && ascii <= 255) {
                length++;
            } else {
                length += 2;
            }
        }
        return length;

    }

}
